package com.example;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Option;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;

public class ReplaceString extends Recipe {
    @Option(displayName = "Old String",
            description = "Old String.",
            example = "oldString")
    String oldString;

    @Option(displayName = "New String",
            description = "New String.",
            example = "newString")
    String newString;

    public ReplaceString(@JsonProperty("oldString") String oldString, @JsonProperty("newString") String newString) {
        this.oldString = oldString;
        this.newString = newString;
    }

    public String getDisplayName() {
        return "ReplaceString";
    }

    public String getDescription() {
        return "Replace all old string with new string.";
    }

    public TreeVisitor<?, ExecutionContext> getVisitor() {
        return new ReplaceStringVisitor(oldString, newString);
    }

    private class ReplaceStringVisitor extends JavaIsoVisitor<ExecutionContext> {
        String oldString;
        String newString;

        ReplaceStringVisitor(String oldString, String newString) {
            this.oldString = oldString;
            this.newString = newString;
        }

        @Override
        public J.Literal visitLiteral(J.Literal literal, ExecutionContext ctx) {
            J.Literal lit = super.visitLiteral(literal, ctx);
            if (lit.getType() == JavaType.Primitive.String && lit.getValue().equals(oldString)) {
                System.out.print("got oldString, newString:" + newString + "\n");
                return lit.withValue(newString).withValueSource('"' + newString + '"');
            }
            System.out.print("no oldString: " + oldString + "\n");
            return lit;
        }
    }
}
